<template>
    <el-select :value="valueTitle"
               :clearable="clearable"
               @clear="clearHandle"
               ref="select"
               :filterable="filterable"
               :disabled="disabled"
               @visible-change="visibleChange"
               :filter-method="dataFilter">
        <el-input
            v-model="valueTitleInput"
            @change="dataFilter"
            ref="input" size="small"
            v-show="showSearch"
            :clearable="true">
        </el-input>
        <el-option :value="valueTitle" :label="valueTitle">
            <el-scrollbar wrap-class="list" view-class="view-box" :native="false" ref="selectScroll"
                          class="scroll-view" v-loading="loading">
                <el-tree id="tree-option"
                         v-if="renderTree"
                         v-show="showTree"
                         ref="selectTree"
                         :accordion="accordion"
                         :default-expand-all="expandAll"
                         :props="props"
                         :data="options"
                         :lazy="lazy"
                         :load="loadNode"
                         :node-key="props.value"
                         :expand-on-click-node="false"
                         :default-expanded-keys="defaultExpandedKey"
                         @node-expand="nodeExpand"
                         @node-collapse="nodeCollapse"
                         @node-click="handleNodeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <i class="iconfont iconwenjianjia small mr10 file"
                           v-if="!(lazy&&!data.expand)&&!(!lazy&&!data.children)||(data.haschildren)"></i>
                        <i class="iconfont iconfuwu small mr10 sys" v-else></i>
                        <!-- <i class="iconfont iconxitong small mr10 sys"
                           v-if="(lazy&&!data.expand)||(!lazy&&!data.children)"></i>
                        <i class="iconfont iconwenjianjia small mr10 file" v-else></i> -->
                        <span class="el-tree-node__label">{{ data.label }}</span>
                    </span>
                </el-tree>
            </el-scrollbar>
        </el-option>
    </el-select>
</template>

<script>
    export default {
        name: 'el-tree-select',
        props: {
            /* 配置项 */
            props: {
                type: Object,
                default: () => {
                    return {
                        value: 'id', // ID字段名
                        label: 'label', // 显示名称
                        children: 'children', // 子级字段名
                        isLeaf: 'isLeaf', // 是否为子节点
                        disabled: 'disabled' // 是否可选
                    }
                }
            },
            /* 选项列表数据(树形结构的对象数组) */
            options: {
                type: Array,
                default: () => {
                    return []
                }
            },
            /* 初始值 */
            value: {
                type: Number,
                default: () => {
                    return null
                }
            },
            /* 是否开启懒加载 */
            lazy: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 是否禁用 */
            disabled: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 是否可搜索 */
            filterable: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 可清空选项 */
            clearable: {
                type: Boolean,
                default: () => {
                    return true
                }
            },
            /* 一次只展开一个同级节点 */
            accordion: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 默认展开所有节点 */
            expandAll: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 重新渲染tree时的loading */
            loading: {
                type: Boolean,
                default: () => {
                    return false
                }
            },
            /* 重新渲染tree */
            renderTree: {
                type: Boolean,
                default: () => {
                    return true
                }
            },
            /* 是否显示搜索框 */
            showSearch: {
                type: Boolean,
                default: () => {
                    return true
                }
            },

            /* 组件当前值 */
            model: {
                type: Object,
                default: () => {
                    return {
                        value: '',
                        label: ''
                    }
                }
            }
        },
        data() {
            return {
                valueId: this.model.value, // 初始值
                valueTitle: '',
                valueTitleInput: '',
                FilterName: '',
                showTree: true,
                defaultExpandedKey: []
            }
        },
        mounted() {
            this.initHandle()
        },
        methods: {
            // 初始化值
            initHandle() {
                if (this.valueId && this.options[0]) {
                    this.valueTitle = this.$refs.selectTree.getNode(this.valueId).data[this.props.label] // 初始化显示
                    this.$refs.selectTree.setCurrentKey(this.valueId) // 设置默认选中
                    this.defaultExpandedKey = [this.valueId] // 设置默认展开
                }
                this.$nextTick(() => {
                    let scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
                    scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
                })
            },
            // 切换选项
            handleNodeClick(node) {
                let _this = this
                this.$emit('nodeClick', node, () => {
                    _this.valueTitle = node[this.props.label]
                    _this.valueId = node[this.props.value]
                    _this.$emit('update:model', {
                        value: this.valueId,
                        label: this.valueTitle
                    })
                    _this.defaultExpandedKey = []
                    _this.$refs.select.blur()
                })
            },
            // 清除选中
            clearHandle() {
                this.valueTitle = ''
                this.valueId = null
                this.defaultExpandedKey = []
                this.clearSelected()
                this.$emit('getValue', null)
            },
            /* 清空选中样式 */
            clearSelected() {
                let allNode = document.querySelectorAll('#tree-option .el-tree-node')
                allNode.forEach((element) => element.classList.remove('is-current'))
            },
            loadNode(node, resolve) {
                let parentId = node.data ? node.data.id : '', _this = this
                this.$emit('loadNode', parentId, data => {
                    setTimeout(() => {
                        _this.$refs.selectScroll.update()
                        _this.$nextTick(() => {
                            if (!parentId && parentId !== 0 && _this.valueId) {
                                if (_this.$refs.selectTree.getNode(_this.valueId)) {
                                    _this.valueTitle = _this.$refs.selectTree.getNode(_this.valueId).data[_this.props.label] // 初始化显示
                                    _this.$refs.selectTree.setCurrentKey(_this.valueId) // 设置默认选中
                                    _this.defaultExpandedKey = [_this.valueId] // 设置默认展开
                                } else {
                                    _this.valueTitle = _this.model.label
                                }
                            }
                        })
                    }, 500)
                    return resolve(data)
                })
            },
            dataFilter($event) {
                let _this = this
                this.$emit('filterMethod', this.valueTitleInput, () => {
                    setTimeout(() => {
                        _this.$refs.selectScroll.update()
                    }, 500)
                })
            },
            /* 有搜索内容时，关闭下拉框重新渲染tree */
            visibleChange(visible) {
                // let _this = this
                // if (!visible && this.$refs.select.$children[0].value) {
                //     this.$emit('update:expandAll', false)
                //     this.$emit('update:renderTree', false)
                //     setTimeout(() => {
                //         _this.$emit('update:lazy', true)
                //         _this.$emit('update:renderTree', true)
                //     }, 300)
                // }
            },
            nodeExpand() {
                this.updateScroll()
            },
            nodeCollapse() {
                this.updateScroll()
            },
            updateScroll() {
                let _this = this
                if (!this.lazy) {
                    setTimeout(() => {
                        _this.$refs.selectScroll.update()
                    }, 300)
                }
            }
        },
        watch: {
            model() {
                this.valueId = this.model.value
                this.valueTitle = this.model.label
                this.initHandle()
            },
            loading(show) {
                if (show) {
                    this.$emit('update:renderTree', false)
                    if (this.lazy) {
                        this.$nextTick(() => {
                            this.$emit('update:expandAll', false)
                            this.$emit('update:renderTree', true)
                            this.showTree = false
                        })
                    } else {
                        this.showTree = true
                    }
                } else if (!show) {
                    this.$emit('update:expandAll', !this.lazy)
                    this.$nextTick(() => {
                        this.$emit('update:renderTree', true)
                        this.showTree = true
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
        height: auto;
        height: 200px;
        padding: 0;
        overflow: hidden;
        overflow-y: auto;
    }

    .el-select-dropdown__item.selected {
        font-weight: normal;
    }

    .el-select-dropdown__item.hover {
        background-color: #fff !important;
    }

    ul li > > > .el-tree .el-tree-node__content {
        height: auto;
        padding: 0 20px;
    }

    .el-tree-node__label {
        font-weight: normal;
    }

    .el-tree > > > .is-current .el-tree-node__label {
        color: #409EFF;
        font-weight: 700;
    }

    .el-tree > > > .is-current .el-tree-node__children .el-tree-node__label {
        color: #606266;
        font-weight: normal;
    }
</style>
